package org.example.config;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.Result;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.BindException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理类
 * 当controller发生异常，该类会捕捉到配置的异常信息，然后进行对应的逻辑处理
 * @Author hxy
 * @Date 2021/3/16 10:50
 * @Version 1.0
 */
@Slf4j
@RestControllerAdvice
public class BindExceptionHandler {
    /**
     * 校验错误拦截处理
     * @param manve
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handlerValidException(MethodArgumentNotValidException manve){
        BindingResult bindingResult = manve.getBindingResult();
        Map<String,String> errorMap=new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            log.error("Data check failure : object{"+fieldError.getObjectName()+"},field{"+fieldError.getField()+
                    "},errorMessage{"+fieldError.getDefaultMessage()+"}");
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return Result.fail(errorMap);
    }

    /**
     * 通用异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler({Exception.class})
    public Result exception(Exception ex){
        String message = ex.getMessage();

        if (message!=null){
            log.error("通用异常异常,错误详情：{},{}", message,ex);
        }else {
            log.error("通用异常异常",ex);

        }

        return Result.fail(message);
    }

    /**
     * 处理缺少参数异常
     * @param ex
     * @return
     */
    @ExceptionHandler({MissingServletRequestParameterException.class})
    public Result missingServletRequestParameterException(MissingServletRequestParameterException ex){
        String parameterName = ex.getParameterName();
        String parameterType = ex.getParameterType();

        log.error("客户端缺少参数[{}],参数类型为类型[{}]", parameterName,parameterType);

        return Result.fail("缺少参数:["+parameterName+"],参数类型：["+parameterType+"]");
    }


}
